package completablefuture;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Function;

/**
 * @description: callback
 * @author: WangPengPeng
 * @create: 2021-11-22 21:33
 **/
public class Demo5TheApply {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(15, 30, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>(2000), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
        Integer count = new Integer(0);
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            for (int i = 0; i < 10; i++) {
                threadPoolExecutor.execute(new MyTask(count));
            }
            System.out.println("异步任务");
            return "abcdefg";
        }).thenApply(new Function<String, Integer>() {
            @Override
            public Integer apply(String middle) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                middle = (middle + "middle");
                System.out.println("获取异步任务中间结果，再次计算返回 : " + middle);
                return middle.length();
            }
        });

        Integer integer = future.get();
        System.out.println("最终结果： " + integer);
        System.out.println("最终结果： " + count);
    }
    static class  MyTask implements Runnable {
        Integer counter;

        public MyTask(Integer counter) {
            this.counter = counter;
            System.out.println("threadName -" + counter + "  " + Thread.currentThread().getName());

        }

        @Override
        public void run() {
            counter++;
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
